package com.rs.controller;

import com.common.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


/**
 * @Author Str
 * @Date 2022/1/10 14:51
 * @Description :
 */
@RestController
@RequestMapping("/ribbon")
public class RibbonController {
    @Autowired
    private LoadBalancerClient client;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取服务列表
     * localhost:9301/ribbon/getServiceInfo
     */
    @GetMapping("/getServiceInfo")
    public String getServiceInfo() {
        // 根据服务名称和负载均衡获取一个服务详情
        ServiceInstance instance = client.choose("DEPT-PROVIDER");
        return instance.toString();
    }

    /**
     * 获取一个服务
     * localhost:9301/ribbon/getDeptById?id=1
     */
    @GetMapping("/getDeptById")
    public String getDeptById(@RequestParam("id")Integer id){
        String url="http://DEPT-PROVIDER/dept/getDeptById?id={0}";
        Dept dept = restTemplate.getForObject(url, Dept.class, id);
        assert dept != null;
        System.out.println("port："+dept.getDeptDesc());
        return "RibbonController.getDeptById：</br>"+dept;
    }


    /**
     * 获取一个超时服务
     * localhost:9301/ribbon/getLongTime
     */
    @GetMapping("/getLongTime")
    public String getLongTime(){
        String url="http://DEPT-PROVIDER/dept/getLongTime";
        String s = restTemplate.getForObject(url, String.class);
        return "RibbonController.getLongTime：</br>"+s;
    }

    /**
     * 获取一个非超时服务
     * localhost:9301/ribbon/getShortTime
     */
    @GetMapping("/getShortTime")
    public String getShortTime(){
        String url="http://DEPT-PROVIDER/dept/getShortTime";
        String s = restTemplate.getForObject(url, String.class);
        return "RibbonController.getShortTime：</br>"+s;
    }

}
